import axios from "axios";
import { ElMessage } from "element-plus";
import router from "@/router";
import { useAllDataStore } from "@/stores";

const envUrl = import.meta.env.VITE_SERVE;
const http = axios.create({
  baseURL: envUrl,
  timeout: 10000,
});

const NETWORK_ERROR = "网络异常，请稍后重试";

// 请求拦截器
http.interceptors.request.use(
  function (config) {
    // 获取token
    const token = localStorage.getItem("token");

    // 不需要携带token的接口路径，建议小写
    const whiteUrl = ["/login/login", "/login/register"];

    // 路径小写方便匹配
    const requestUrl = config.url ? config.url.toLowerCase() : "";

    // 如果有token且请求路径不在白名单，添加 Authorization 头
    if (token && !whiteUrl.includes(requestUrl)) {
      config.headers["Authorization"] = `Bearer ${token}`;
    }

    return config;
  },
  function (error) {
    return Promise.reject(error);
  }
);

// 响应拦截器
http.interceptors.response.use(
  function (response) {
    const store = useAllDataStore();

    if (response.data.code === 403) {
      ElMessage.warning("登录已过期，请重新登录");
      localStorage.removeItem("token");
      store.clean();
      router.push("/login");
      return Promise.reject(new Error("登录已过期"));
    }

    return response;
  },
  function (error) {
    ElMessage.error(NETWORK_ERROR);
    return Promise.reject(error);
  }
);

export default http;
